﻿using Pattern12享元模式.Base;
using Pattern12享元模式.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pattern12享元模式.Services
{
    public class PieceFactory
    {
        //防止实例化，只允许通过静态类获取唯一实例
        private PieceFactory()
        {

        }

        private static readonly PieceFactory instance = new PieceFactory();
        public static PieceFactory Instance=>instance;

        public Hashtable hashtable { get; set; } = new Hashtable();//存储享元对象

        public Piece GetPiece(string key)
        {
            if(hashtable.ContainsKey(key))
            {
                return (Piece)hashtable[key];   //有对象就直接返回对象
            }

            if (key == "黑")
            {
                Piece piece = new BlackPiece();
                hashtable.Add(key, piece);
                return piece;
            }
            else if (key == "白")
            {
                Piece piece = new WhitePiece();
                hashtable.Add(key, piece);
                return piece;
            }
            else
            {
                return null;
            }
        }
    }
}
